package com.zlc.common.config;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.zlc.common.common.service.ContextHolder;
import com.zlc.common.util.PlatUtils;
import com.zlc.common.util.UserHelper;
import org.apache.ibatis.reflection.MetaObject;

import java.util.Date;

import static com.zlc.common.common.constant.PlatConstant.AOP_KEY_WORD;

/**
 * mybatis plus这个功能有bug  会影响乐观锁实现
 */
//@Component
public class MyMetaObjectHandler implements MetaObjectHandler {

    @Override
    public void insertFill(MetaObject metaObject) {
        addField(metaObject,true);
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        addField(metaObject,false);
    }


    public static void addField(MetaObject metaObject,boolean insert) {
        Object keyWord = ContextHolder.get(AOP_KEY_WORD);
        if (keyWord != null) {
            return;
        }
        metaObject.setValue("id",PlatUtils.uuid());

        // 设置通用属性
        String userName = UserHelper.getNowAccount();
        if (userName == null) {
            userName = ContextHolder.get("logAccount");
        }
        if (userName == null) {
            userName = "SYSTEM";
        }
        metaObject.setValue("createUser",userName);
        metaObject.setValue("updateUser",userName);
        if(insert){
            metaObject.setValue("createTime",new Date());
        }
        metaObject.setValue("updateTime",new Date());
    }
}
